<?php
/*
 * Created on 25 Jan 2009
 *
 * Daniel Mitchell
 * 
 * Upload script, works in conjunction with UserConfig scripts to check user permissions
 */
require_once "script/real_path.php"; 
require_once "UserConfig.php";
require_once "FileXML.php";

$name = $_REQUEST['user']; //the username to login with
$pass = $_REQUEST['pass']; //the password to login with
$path = $_REQUEST['dir']; //the directory to upload to, will be part of the overall file name
$checkInName = $_REQUEST['checkinname']; //only used if the file being uploaded is to be checked in and overwrites a exsiting file
$action = $_REQUEST['action']; //the action to be performed, either 'upload' or 'checkIn' 
$filename = $_FILES['uploadFile']['name']; //the filename of the file being uploaded, used if new file
 
$userConfig = new UserConfig();
$fileXML = new FileXML();
$user = $userConfig->loginUser($name, $pass);
if($action == "upload")
	$filename = real_path( $path ."/". basename($_FILES['uploadFile']['name'])); //echo "Upload location: ".$filename."<br />";
else if($action == "checkIn")
	$filename = real_path( $path ."/". $checkInName);//used if the file is supposed to be checked in, this causes the current file to be overwitten
	

//gets the user and checks to see if they have the overwrite permission
$user = $userConfig->_getUser();
if(!$userConfig->_hasPermission($user, 'overwrite') && file_exists($filename)) exit;

//This section gets the file extensions that the user is allowed to user and compares it to the file trying
//to be uploaded
$uploadfilter = $user['uploadfilter']['type'];
$typearr = explode(';', $uploadfilter);
for ($i=0;$i<count($typearr);$i++){
	$typearr[$i] = substr($typearr[$i],2); 
}
$namearr = explode('.',$_FILES['uploadFile']['name']);
if (count($namearr)>=2) {
	$ext = strtolower($namearr[count($namearr)-1]);
	if (!in_array($ext, $typearr) && !in_array('*', $typearr)) exit;
}

//Final part moves the file from its temp location
if(move_uploaded_file( $_FILES['uploadFile']['tmp_name'] , $filename )){
	$foldername = explode("/", $path);
	if($action == "upload")
		$fileXML->push_new_file($foldername[count($foldername)-1], basename($_FILES['uploadFile']['name']), $name);
	else if($action == "checkIn")
		$fileXML->updateCheckOut($foldername[count($foldername)-1], $checkInName, 1, $name);
	echo "success";
}

//echo 1;
?>
